package com.example.yilanchatserver.application.controller;

import com.alibaba.fastjson.JSON;
import com.example.yilanchatserver.business.freechat.service.ChatGPTService;
import com.example.yilanchatserver.business.freechat.service.dto.FreeChatDTO;
import com.example.yilanchatserver.business.freechat.BaseResponseEntity;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;

@ServerEndpoint(value = "/metah/freechat/chatgpt/stream")
@Component
public class ChatGPTWebSocketServer {
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<ChatGPTWebSocketServer> webSocketSet = new CopyOnWriteArraySet<ChatGPTWebSocketServer>();



    private static ChatGPTService chatGPTService;

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

//    public ChatGPTWebSocketServer_metah(){
//        this.chatGPTService = SpringUtil.getBean(ChatGPTService.class);
//    }
    @Resource
    private void setChatGPTService(ChatGPTService chatGPTService){
        ChatGPTWebSocketServer.chatGPTService = chatGPTService;

    }



    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this); //加入set中
        addOnlineCount(); //在线数加1

//        String img1 = "img1";
//        String img2 = "img2";

        int cnt = 0;
//        try {
//            sendMessage("连接成功");
//            System.out.println("连接成功");
//        } catch (IOException e) {
//
//        }
    }

    /**
     * 图片转base64字符串
     *
     * @param imgFile 图片路径
     * @return
     */
    public static String imageToBase64Str(String imgFile) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 加密
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this); //从set中删除
        subOnlineCount(); //在线数减1

    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param inputQuestion 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String inputQuestion, Session session) throws IOException {
        for (ChatGPTWebSocketServer item : webSocketSet) {
            if(item.session!=session){
                continue;
            }
            FreeChatDTO freeChatDTO = JSON.parseObject(inputQuestion, FreeChatDTO.class);
            Flux<String> response = chatGPTService.send(freeChatDTO);
            response.subscribe(message -> {
                try {
                    if(!"[Done]".equals(message)){
                        item.sendMessage(BaseResponseEntity.SUCCESS(message));
                        TimeUnit.MILLISECONDS.sleep(20);
                    }
                    else{
                        item.sendMessage(BaseResponseEntity.FINISH());
                        item.closeSession();
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });

//            item.closeSession();
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {

        error.printStackTrace();
    }

    public void closeSession() throws IOException {
        this.session.close();
    }

    public void sendMessage(BaseResponseEntity baseResponseEntity) throws IOException {
        String message = JSON.toJSONString(baseResponseEntity);
        if(this.session.isOpen()){
            this.session.getBasicRemote().sendText(message);
        }
        else{
            webSocketSet.remove(this);
        }

    }


    /**
     * 群发自定义消息
     * */
//    public static void sendInfo(String message) throws IOException {
//
//        for (CharacterChatWebSocketServer item : webSocketSet) {
//            try {
//                item.sendMessage(message);
//            } catch (IOException e) {
//                continue;
//            }
//        }
//    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        ChatGPTWebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        ChatGPTWebSocketServer.onlineCount--;
    }
}


